<template>
  <div style="width: 100%">
    <span v-if="props.showText">{{currName}}</span>
    <el-select
      v-else
      v-model="modelValue"
      class="select"
      :disabled="disabled"
      :size="size"
      :filterable="props.filterable"
      :placeholder="calcPlaceholder"
      @change="handleChange"
      clearable
    >
      <el-option v-for="item in options"
        :key="item.key"
        :value="item.key"
        :label="item.value"
        :disabled="item.disabled === true"
      />
    </el-select>
  </div>
</template>

<script setup>
import { ref, watch, computed } from 'vue';
import { getDictionary } from '@/utils/system';
import { useDisabled } from 'element-plus';

const emit = defineEmits(['change']);
const props = defineProps({
  dictCode: String,
  filterable: {
    type: Boolean,
    default: true,
  },
  placeholder: {
    type: String,
    default: '--请选择--'
  },
  size: {
    type: String,
    default: 'default'
  },
  disabled: Boolean,
  showText: Boolean
});

const modelValue = defineModel();
const currName = ref('');
const options = ref([]);
const inputDisabled = useDisabled();

const handleChange = () => {
  emit('change');
};

const loadDicAndShow = async(dictCode) => {
  if ((dictCode || '') === '') {
    options.value = [];
  } else {
    options.value = await getDictionary(dictCode);
  }
  calcValue();
};

const calcValue = () => {
  currName.value = '';
  if (props.showText) {
    options.value.forEach(option => {
      if (option.key === modelValue.value) {
        currName.value = option.value;
      }
    });
  }
};

const disabled = computed(() => {
  return props.disabled || inputDisabled.value;
});

const calcPlaceholder = computed(() => {
  return disabled === true ? '' : props.placeholder;
});

watch(() => props.dictCode, (dictCode) => {
  loadDicAndShow(dictCode);
}, {immediate: true});

watch(() => modelValue.value, () => {
  calcValue();
});
</script>

<style scoped>
.select {
  width: 100%;
}
</style>